package com.zerdoor.controller;

import com.zerdoor.model.UserInfo;
import com.zerdoor.service.ITaskInfoService;
import com.zerdoor.util.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by zhongjieyu on 2014/11/03.
 * 文件上传控制层
 */
@Controller
@RequestMapping("/fileUpload")
public class FileUploadController {


    /**
     *
     *@描述:附件文件Ajax上传
     *@return ResponseEntity<?>
     *@作者：zjy
     *@创建日期： 2014年5月26日09:48:59
     */
    @RequestMapping(value = "/upload_resource_file", method = RequestMethod.POST)
    public  void upload_resource_file(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request,final HttpServletResponse response, ModelMap model) {
        try {


            //读取上传文件相对路径
//            String fileUrl = ReadProperties.getInstance().getValue("/META-INF/system.properties","mis_flie_upload_url");
            String fileUrl = "uploads/task";
            //得到上传文件绝对路径
            String path = request.getSession().getServletContext().getRealPath(fileUrl);
            String fileName = file.getOriginalFilename(); //文件原名

            //去掉文件名中的空格，避免下载出错
            fileName = fileName.replaceAll(" ","");

            if("".equals(fileName)){
                return;
            }
            //文件夹名
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String folderName = sdf.format(new Date().getTime());

            UserInfo user = (UserInfo)request.getSession().getAttribute("curUser");
            path += "//"+user.getUserId() + "//"+folderName;

            //创建文件夹及文件
            File targetFile = Tools.getFileByOriginalFileName(path,fileName,2);


            //保存文件
            file.transferTo(targetFile);

            String new_fileName = targetFile.getName();



            String strUrl = fileUrl+"/"+user.getUserId()+"/" + folderName +"/"+ new_fileName;

            //设置返回头
            response.setContentType("text/html");
            response.getWriter().print(strUrl+","+new_fileName);

        } catch (Exception e) {
            //log.error(e.getMessage(), e);
            e.printStackTrace();
        }
    }







}
